package com.dl.filter;

import com.alibaba.fastjson.JSONObject;
import com.dl.config.jwt.BaseResponse;
import com.dl.config.jwt.JwtTokenManager;
import com.dl.properties.JWTProperties;
import com.dl.utils.ConstantField;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 自定义登录验证过滤器
 * @author DL
 * @create 2021-06-15 11:58
 */
public class JwtRolesFilter extends RolesAuthorizationFilter {

    private final JWTProperties jwtProperties;

    private final JwtTokenManager jwtTokenManager;

    public JwtRolesFilter(JWTProperties jwtProperties, JwtTokenManager jwtTokenManager) {
        this.jwtProperties = jwtProperties;
        this.jwtTokenManager = jwtTokenManager;
    }

    //表示访问拒绝时是否自己处理，如果返回true表示自己不处理且继续拦截器链执行，返回false表示自己已经处理了（比如重定向到另一个页面）。
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        //判断当前请求头中是否带有jwtToken的字符串
        String jwtToken = WebUtils.toHttp(request).getHeader(jwtProperties.getJwtTokenName());
        //如果有，返回json格式应答
        if (!StringUtils.isEmpty(jwtToken)) {
            BaseResponse baseResponse = new BaseResponse(ConstantField.NO_ROLE_CODE, ConstantField.NO_ROLE_MESSAGE);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;utf-8");
            response.getWriter().write(JSONObject.toJSONString(baseResponse));
        }
        //如果没有，原始方式应答
        return super.onAccessDenied(request, response);
    }

}
